package com.qf.mybatisplus.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author: zhudadi
 * @create: 2023/4/10 18:18
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext appCtx;

    /**
     * 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。
     *
     * @param applicationContext ApplicationContext 对象.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtx = applicationContext;
    }

    /**
     * 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return appCtx;
    }

    /**
     * 这是一个便利的方法，帮助我们快速得到一个BEAN
     *
     * @param beanName bean的名字
     * @return 返回一个bean对象
     */
    public static Object getBean(String beanName) {
        return appCtx.getBean(beanName);
    }

    public static <T> T getBean(Class<T> var1) {
        return appCtx.getBean(var1);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return appCtx.getBean(beanName, clazz);
    }

    /**
     * 获取当前环境
     * @return
     */
    public static String getActiveProfile() {
        String[] profiles = appCtx.getEnvironment().getActiveProfiles();
        if (profiles.length == 0) {
            return "dev";
        }
        return profiles[0];
    }

    /**
     * 是否生产环境
     * @return
     */
    public static boolean isProduct(){
        return "prod".equals(getActiveProfile());
    }

    /**
     * 非生产环境
     * @return
     */
    public static boolean isNotProduct(){
        return !isProduct();
    }


    public static String getProductName() {
        Environment environment = getBean(Environment.class);
        return StringUtils.defaultIfBlank(environment.getProperty("log.app.name"), "");
    }
}